package cn.tedu.csmall.business.controller;

import cn.tedu.csmall.business.service.IBusinessService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "业务触发模块")
@RestController
@RequestMapping("/base/business")
@Slf4j
public class BusinessController {
    @Autowired
    private IBusinessService service;
    @PostMapping("/buy")
    @ApiOperation("执行业务触发")
    @SentinelResource(value = "购买触发器",blockHandler = "blockError",fallback ="fallbackError")
    public JsonResult buy(){
//        service.buy();
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if(Math.random()<0.5){
            throw new CoolSharkServiceException(
                    ResponseCode.INTERNAL_SERVER_ERROR,"发生随机异常");
        }
        return JsonResult.ok("购买完成");
    }

    public JsonResult blockError(BlockException e){
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"business服务器忙");
    }
    public JsonResult fallbackError(Throwable e){
        e.printStackTrace();
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"business服务降级");
    }

}
